package FrameWork.Executor;

import java.util.concurrent.*;

public class EventLoop {

    private ScheduledExecutorService executorService;
    private EventLoopThread bindThread;
    private EventLoopGroup parent;
    private int dispatcherCode;

    EventLoop(EventLoopGroup parent, ThreadFactory factory,int code){
        this.parent = parent;
        this.dispatcherCode = code;
        executorService = Executors.newScheduledThreadPool(1,factory);
        submit(this::init);
    }

    public void submit(Runnable runnable){
        executorService.submit(runnable);
    }

    public ScheduledFuture setTimer(long delay,Runnable runnable){
       return executorService.schedule(runnable,delay, TimeUnit.MILLISECONDS);
    }

    public ScheduledFuture setPeriod(long delay, Runnable runnable){
        return executorService.scheduleAtFixedRate(runnable,delay,delay,TimeUnit.MILLISECONDS);
    }


    private void setBindThread(EventLoopThread thread){
        this.bindThread = thread;
    }


    private void init(){
        EventLoopThread eventLoopThread = (EventLoopThread)Thread.currentThread();
        eventLoopThread.setEventLoop(this);
        eventLoopThread.setEventLoopGroup(this.parent);
        setBindThread(eventLoopThread);
        System.out.println(eventLoopThread.getName()+"启动成功");
        parent.countDown();
    }

    public int getDispatcherCode() {
        return dispatcherCode;
    }
}
